//
//  SectionsViewController.m
//  DataStatistics
//
//  Created by Kang on 16/3/8.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "SectionsViewController.h"
#import "YJLocalCountryData.h"
#import <SMS_SDK/Extend/SMSSDKCountryAndAreaCode.h>
#import <SMS_SDK/SMSSDK.h>

@interface SectionsViewController () {
    NSMutableData* _data;
    NSMutableArray* _areaArray;
}
@end

@implementation SectionsViewController
@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize search;
@synthesize allNames;

#pragma mark Custom Methods
// 搜索方法
- (void)resetSearch
{
    NSMutableDictionary* allNamesCopy = [YJLocalCountryData mutableDeepCopy:self.allNames];
    self.names = allNamesCopy;
    NSMutableArray* keyArray = [NSMutableArray array];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];

    self.keys = keyArray;
}
#pragma mark - 首字母搜索
- (void)HandleSearchForFirstStr:(NSString *)searcherm {
    NSMutableArray *sectionsTorRemove = [NSMutableArray array];
    [self resetSearch];
    for (NSString* key in  self.keys) {
        NSMutableArray *array = [names valueForKey:key];
        NSMutableArray *toRemove = [NSMutableArray array];
        for (NSString *name in array) {
            if (![name.uppercaseString hasPrefix:searcherm.uppercaseString] || ![name.lowercaseString hasPrefix:searcherm.lowercaseString]) {
                [toRemove addObject:name];
            }
        }
        if ([array count] == [toRemove count]) {
            [sectionsTorRemove addObject:key];
        }
        [array removeObjectsInArray:toRemove];
        
    }
    [self.keys removeObjectsInArray:sectionsTorRemove];
    [table reloadData];
    
}
#pragma mark - 模糊查询
- (void)HandleSearchForTerm:(NSString*)searcherm
{
    NSMutableArray* sectionsToRemove = [NSMutableArray array];
    [self resetSearch];

    for (NSString* Key in self.keys) {
        NSMutableArray* array = [names valueForKey:Key];
        NSMutableArray* toRemove = [NSMutableArray array];
        for (NSString* name in array) {
            if ([name rangeOfString:searcherm options:NSCaseInsensitiveSearch].location == NSNotFound) {
                [toRemove addObject:name];
            }
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:Key];
        [array removeObjectsInArray:toRemove];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [table reloadData];
}
- (void)setareaArray:(NSMutableArray*)array
{
    _areaArray = [NSMutableArray arrayWithArray:array];
}

#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [keys count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return 0;

    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];
    return [nameSection count];
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSUInteger section = [indexPath section];
    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];

    static NSString* SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:SectionsTableIdentifier];
        cell.backgroundColor = [UIColor blackColor];
    }

    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range = [str1 rangeOfString:@"+"];
    NSString* str2 = [str1 substringFromIndex:range.location];
    NSString* areaCode = [str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryNamae = [str1 substringToIndex:range.location];

    cell.textLabel.text = countryNamae;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"+%@", areaCode];
    return cell;
}

- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return 0;

    NSString* key = [keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;

    return key;
}
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
    if (isSearching)
        return nil;
    return keys;
}

#pragma mark TableViewDelegate Methods
- (NSIndexPath*)tableView:(UITableView*)tableView willSelectRowAtIndexPath:(nonnull NSIndexPath*)indexPath
{
    [search resignFirstResponder];
    search.text = @"";
    isSearching = NO;
    [tableView reloadData];
    return indexPath;
}
// 修改头部组的
- (void)tableView:(UITableView*)tableView willDisplayHeaderView:(UIView*)view forSection:(NSInteger)section
{
    view.tintColor = RGB(40, 51, 67, 1);

    UITableViewHeaderFooterView* header = (UITableViewHeaderFooterView*)view;
    [header.textLabel setTextColor:[UIColor whiteColor]];
}

- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index
{
    NSString* key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else
        return index;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSUInteger section = [indexPath section];
    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];

    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range = [str1 rangeOfString:@"+"];
    NSString* str2 = [str1 substringFromIndex:range.location];
    NSString* areaCode = [str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryNmae = [str1 substringToIndex:range.location];

    SMSSDKCountryAndAreaCode* country = [[SMSSDKCountryAndAreaCode alloc] init];
    country.countryName = countryNmae;
    country.areaCode = areaCode;

    NSLog(@"----%@ --- %@", countryNmae, areaCode);
    [self.view endEditing:YES];

    int comparResult = 0;
    for (int i = 0; i < _areaArray.count; i++) {
        NSDictionary* dict1 = [_areaArray objectAtIndex:i];

        [dict1 objectForKey:areaCode];
        NSString* code1 = [dict1 valueForKey:@"zone"];
        if ([code1 isEqualToString:areaCode]) {
            comparResult = 1;
            break;
        }
    }

    if (!comparResult) {

        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"notice", nil)
                                                        message:NSLocalizedString(@"doesnotsupportarea", nil)
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"sure", nil)
                                              otherButtonTitles:nil, nil];
        [alert show];
        return;
    }

    if ([self.delegate respondsToSelector:@selector(setSecondData:)]) {
        [self.delegate setSecondData:country];
    }

    [self clickLeftButton];
}

#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar*)searchBar
{
    NSString* searchTerm = [searchBar text];
    [self HandleSearchForFirstStr:searchTerm];
   // [self HandleSearchForTerm:searchTerm];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar*)searchBar
{
    isSearching = YES;
    [table reloadData];
}

- (void)searchBar:(UISearchBar*)searchBar
    textDidChange:(NSString*)searchTerm
{
    if ([searchTerm length] == 0) {
        [self resetSearch];
        [table reloadData];
        return;
    }

   // 首字母搜索
    [self HandleSearchForFirstStr:searchTerm];
}
- (void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
{
    isSearching = NO;
    search.text = @"";

    [self resetSearch];
    [table reloadData];

    [searchBar resignFirstResponder];
}

- (void)clickLeftButton
{
    //    [self dismissViewControllerAnimated:YES completion:^{
    //        ;
    //    }];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor]; //黑色
    self.title = NSLocalizedString(@"choose", nil);
    CGFloat statusBarHeight = 0;
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
            statusBarHeight = 20;
        }

    //搜索头部
        search = [[UISearchBar alloc] init];
       // search.frame = CGRectMake(0,statusBarHeight, self.view.frame.size.width, 44);
        search.frame = CGRectMake(0,0, self.view.frame.size.width, 44);
        search.barTintColor = [UIColor clearColor];
        [self.view addSubview:search];
         table = [[UITableView alloc] initWithFrame:CGRectMake(0, 44 , self.view.frame.size.width, self.view.bounds.size.height - (44 + statusBarHeight)) style:UITableViewStylePlain];
        // table = [[UITableView alloc] initWithFrame:CGRectMake(0, 44 + statusBarHeight, self.view.frame.size.width, self.view.bounds.size.height - (44 + statusBarHeight)) style:UITableViewStylePlain];
    
     [[UITableViewHeaderFooterView appearance] setTintColor:RGB(40, 51, 67, 1)];
  //  table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];

    table.backgroundColor = [UIColor blackColor];
    table.sectionIndexBackgroundColor = [UIColor blackColor];
    [self.view addSubview:table];

    table.dataSource = self;
    table.delegate = self;
    search.delegate = self;

    NSString* path = [[NSBundle mainBundle] pathForResource:@"country" ofType:@"plist"];
    NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.allNames = dict;
    [self resetSearch];
    [table reloadData];
     [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO]; //添加搜索框时
   // [table setContentOffset:CGPointMake(0.0, 0.0) animated:NO];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
